<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">名称：</label>
                                    <div class="layui-input-inline">
                                        <input name="name" class="layui-input" type="text" placeholder="请输入名称"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">编号：</label>
                                    <div class="layui-input-inline">
                                        <input name="code" class="layui-input" type="text" placeholder="请输入编号"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">状态：</label>
                                    <div class="layui-input-inline">
                                        <select name="status">
                                            <option value="">请选择状态</option>
                                            <option value="working">工作中</option>
                                            <option value="standby">待机</option>
                                            <option value="damage">损坏</option>
                                            <option value="deactivate">停用</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">创建时间：</label>
                                    <div class="layui-input-inline">
                                        <input name="createTime" id="pTime" class="layui-input date-icon" type="text"
                                               placeholder="选择时间" style="width: 200px" readonly/>
                                    </div>
                                    <input name="startCreateTime" id="sTime" type="hidden"/>
                                    <input name="endCreateTime" id="eTime" type="hidden"/>
                                </div>
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog" layui-form-keyDownSearch="true" lay-submit>查询</button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置</button>
                                </div>
                            </div>
                            <div class="query-rt"></div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="robotArmBtnAdd" class="layui-btn icon-btn color-reseda">添加</button>
                        </div>
                        <div class="lay-btn-rt">
                        </div>
                    </div>
                </div>
            </div>

            <!-- 表格 -->
            <table class="layui-table" id="robotArmTable" lay-filter="robotArmTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="robotArmTableBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="test">测试</a>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="robotArmForm">
    <form lay-filter="robotArmForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label">名称</label>
            <div class="layui-input-block">
                <input name="name" placeholder="请输入名称" type="text" class="layui-input" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">编号</label>
            <div class="layui-input-block">
                <input name="code" placeholder="请输入编号" type="text" class="layui-input" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">品牌</label>
            <div class="layui-input-block">
                <input name="brand" placeholder="请输入品牌" type="text" class="layui-input" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">ip地址</label>
            <div class="layui-input-block">
                <input name="ipAddress" placeholder="请输入ip地址" type="text" class="layui-input" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">绑定AGV</label>
            <div class="layui-input-block">
                <select name="agvId" id="agvId" lay-filter="agvId" lay-verify="required"
                        required></select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">状态</label>
            <div class="layui-input-block">
                <select name="status">
                        <option value="working">工作中</option>
                        <option value="standby">待机</option>
                        <option value="damage">损坏</option>
                        <option value="deactivate">停用</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="robotArmFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<script type="text/html" id="testForm">
    <form lay-filter="testForm" class="layui-form model-form">
        <div class="layui-form-item">
            <label class="layui-form-label">服务ip</label>
            <div class="layui-input-block">
                <input name="serIp" id="serIp" placeholder="服务ip" type="text" class="layui-input" />
            </div>
        </div>


        <div class="layui-form-item" style="margin-top: 30px">
            <label class="layui-form-label"></label>
            <a id="robotTaskAddAgv" class="layui-btn">添加</a>
        </div>
        <div class="agvBox" id="agvBox">
            <div class="layui-row">
                <div class="layui-form-item">
                    <label class="layui-form-label">取货点</label>
                    <div class="layui-input-block">
                            <select name="one" id="one" lay-filter="armId" ></select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">送货点</label>
                    <div class="layui-input-block">
                        <select name="two" id="two" lay-filter="armId" ></select>
                        <a class="layui-btn layui-btn-danger layui-btn-xs agvDel"><i class="layui-icon">&#x1006;</i></a>
                    </div>
                </div>
            </div>
        </div>

        <div class="layui-form-item text-right">
            <button class="layui-btn" lay-filter="action" id="action" type="button">运动</button>
            <button class="layui-btn" lay-filter="catch" id="catch" type="button">抓</button>
            <button class="layui-btn" lay-filter="relax" id="relax" type="button">放</button>
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
        </div>
    </form>
</script>
<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin', 'laydate'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        var laydate = layui.laydate;

        //时间范围
        laydate.render({
            elem: '#pTime',
            type: 'date',
            range: true,
            done: function (value, date, endDate) {
                if (value) {
                    var dateValue = value.split(" - ");
                    $("#sTime").val(dateValue[0] + " 00:00:00");
                    $("#eTime").val(dateValue[1] + " 23:59:59");
                } else {
                    $("#sTime").val();
                    $("#eTime").val();
                }
            }
        });
        
        // 渲染表格
        var insTb = table.render({
            elem: '#robotArmTable',
            url: config.base + 'enterprise/robot/admin/robotArm/list',
            page: true,
            cellMinWidth: 100,
            cols: [[
                {field: 'number', title: '序号',type: 'numbers' }
                ,{field: 'name', sort: true, title: '名称'}
                ,{field: 'code', sort: true, title: '编号'}
                ,{field: 'brand', sort: false, title: '品牌'}
                ,{field: 'ipAddress', sort: false, title: 'ip地址'}
                ,{field: 'agvId', sort: false, title: '绑定AGV',templet:function(d){
                        let map = '';
                        admin.reqSync('enterprise/robot/admin/robotAgv/list', {id: d.agvId}, function (res) {
                            if (200 == res.code&&res.data.length!=0) {
                                map =  res.data[0].name;
                            }
                        }, 'GET', true);
                        return map;
                    }
                }
                ,{field: 'statusDesc', sort: false, title: '状态'}
                ,{field: 'creatorName', sort: true, title: '添加人'}
                ,{field: 'createTime', sort: true, title: '添加时间'}
                ,{align: 'center', toolbar: '#robotArmTableBar', title: '操作', width: 200}
            ]],
            done: function (res, curr, count) {
            }
        });

        // 工具条点击事件
        table.on('tool(robotArmTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') { //修改
                showEditModel(data);
            } else if (obj.event === 'del') { // 删除
                doDelete(obj);
            }
            else if (obj.event === 'test') { // 测试
                doTest(obj);
            }
        });

        function doTest(obj){
            admin.open({
                type: 1,
                area: '680px',
                offset: '65px',
                title:  '测试',
                content: $('#testForm').html(),
                success: function () {
                    $('#robotTaskAddAgv').click(function () {
                        let html = $('#agvBox > .layui-row').eq(0).clone().attr('id', '');
                        $('#agvBox').append(html);
                        form.render('select');
                    });

                    $('#agvBox').delegate('.agvDel', 'click', function () {
                        $(this).parents('.layui-row').remove();
                    });

                    admin.req('enterprise/robot/admin/robotPoint/list', {}, function (res) {
                        if (200 == res.code) {
                            loadSelectHtml(res.data, "请选择点位", "one", 0);
                            loadSelectHtml(res.data, "请选择点位", "two", 0);
                        }else {
                            layer.msg('获取点位失败', {icon: 2, time: 1000});
                        }
                    }, 'GET', true);


                    let serIp = $('#serIp').val();

                    $('#action').click(function(){
                        //机械臂初始位置  固定值
                        let init = {
                            "ip":obj.data.ipAddress,
                            "data":'-1.5496800913477171,1.7057027122529518,-2.616803392360524,2.5182571129455353,1.5927154421174152,-0.8100496977377328'
                        };
                        //本身放货的位置
                        let area=['-1.5495362806517448,1.4351109035564855,-2.6171749033251195,2.7838035630583087,1.5865915033139297,-0.8100377135130685',
                            '-1.8872277632439338,1.4501151528362575,-2.667221025523465,2.8418431631077783,1.6034293389673482,-1.1430433642614948',
                            '-2.239587936825293,1.425942971688254,-2.5840864590268358,2.718956923399485,1.6161086486622358,-1.4121611133242458']  //固定三个测试

                        //取货的位置
                        let infoList=[];
                        let dataList=[]

                        //放货的位置
                        let endInfo = [];
                        let end = [];

                        $('#agvBox>.layui-row').each((index, elem) => {
                            infoList[index] = $(elem).find('select[name="one"]').val();
                            endInfo[index] = $(elem).find('select[name="two"]').val();
                        });
                        for (let i = 0; i <infoList.length ; i++) {
                            admin.reqSync('enterprise/robot/admin/robotPoint/list', {id:infoList[i]}, function (res) {
                                let data=res.data[0].positionOne+','+res.data[0].positionTwo+','+res.data[0].positionThree+','+res.data[0].positionFour+','+res.data[0].positionFive+','+res.data[0].positionSix;
                                dataList[i]=data
                            }, 'GET', true);
                        }
                        for (let i = 0; i <infoList.length ; i++) {
                            admin.reqSync('enterprise/robot/admin/robotPoint/list', {id:endInfo[i]}, function (res) {
                                let data=res.data[0].positionOne+','+res.data[0].positionTwo+','+res.data[0].positionThree+','+res.data[0].positionFour+','+res.data[0].positionFive+','+res.data[0].positionSix;
                                end[i]=data
                            }, 'GET', true);
                        }
                        console.log(dataList)
                        console.log(end)

                        for (let i = 0; i <dataList.length ; i++) {
                            //取货
                            let armParam={
                                "ip":obj.data.ipAddress,
                                "data":dataList[i]
                            }
                            //本身
                            let areaParam={
                                "ip":obj.data.ipAddress,
                                "data":area[i]
                            }


                            admin.req(serIp+':9999/jointMove',armParam,function(res){
                                if(res.code==200){
                                    admin.req(serIp+':9999/jointMove',areaParam,function(res){
                                        if(res.code==200&&i==dataList.length-1){
                                            admin.req(serIp+':9999/jointMove',init,function(res){
                                                if(res.code==200){
                                                    //送货
                                                    for (let j = 0; j <end.length ; j++) {
                                                        //送货
                                                        let endParam={
                                                            "ip":obj.data.ipAddress,
                                                            "data":end[j]
                                                        }
                                                        //本身  送货时的取货位置
                                                        let startParam={
                                                            "ip":obj.data.ipAddress,
                                                            "data":area[j]
                                                        }
                                                        admin.req(serIp+':9999/jointMove',startParam,function(res){
                                                            if(res.code==200){
                                                                admin.req(serIp+':9999/jointMove',endParam,function(res){
                                                                    if(res.code==200&&i==dataList.length-1){
                                                                        admin.req(serIp+':9999/jointMove',init,function(res){

                                                                        },'POST', true);
                                                                    }
                                                                },'POST', true);
                                                            }
                                                        },'POST', true);
                                                    }
                                                }
                                            },'POST', true);
                                        }
                                    },'POST', true);
                                }
                            },'POST', true);
                        }
                    });



                    $('#catch').click(function(){
                        admin.req(serIp+':9999/action',{ip:obj.data.ipAddress},function(res){
                        },'GET', true);
                    });

                    $('#relax').click(function(){
                        admin.req(serIp+':9999/relax',{ip:obj.data.ipAddress},function(res){
                        },'GET', true);
                    });

                }
            });
        }


        //监听排序
        table.on('sort(robotArmTable)', function(obj){
            table.reload('robotArmTable', {
                initSort: obj
                ,where: {
                    sort: obj.field
                    ,order: obj.type
                }
            });
        });


        // 添加按钮点击事件
        $('#robotArmBtnAdd').click(function () {
            showEditModel();
        });

        // 显示编辑弹窗
        function showEditModel(data) {
            admin.open({
                type: 1,
                area: '680px',
                offset: '65px',
                title: data ? '修改机器人机械臂信息' : '添加机器人机械臂信息',
                content: $('#robotArmForm').html(),
                success: function () {
                    if (!data){
                        admin.req('enterprise/robot/admin/robotAgv/list?type=collaboration', {limit: 9999}, function (res) {
                            if (200 == res.code) {
                                loadSelectHtml(res.data, "请选择AGV", "agvId", 0);
                            }else {
                                layer.msg('获取AGV失败', {icon: 2, time: 1000});
                            }
                        }, 'GET', true);
                    }
                    if (data){
                        admin.reqSync('enterprise/robot/admin/robotAgv/list?type=collaboration', {limit: 9999}, function (res) {
                            if (200 == res.code) {
                                loadSelectHtml(res.data, "请选择AGV", "agvId", 0);
                            }else {
                                layer.msg('获取AGV失败', {icon: 2, time: 1000});
                            }
                        }, 'GET', true);
                        var option = $("form select[name='status']").find("option");
                        layui.each(option, function(index, item){
                            if(data.status  == item.text){
                                data.status = item.value;
                            }
                        });
                    }
                    form.val('robotArmForm', data);
                    // 表单提交事件
                    form.on('submit(robotArmFormSubmit)', function (d) {
                        layer.load(2);
                        admin.req(data ? 'enterprise/robot/admin/robotArm/update' : 'enterprise/robot/admin/robotArm/add', d.field, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('robotArmTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, data ? 'PUT' : 'POST');
                        return false;
                    });
                }
            });
        }

        // 删除
        function doDelete(obj) {
            layer.confirm('确定要删除吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('enterprise/robot/admin/robotArm/' + obj.data.id, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        obj.del();
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'DELETE');
            });
        }

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
        });

        // 重置搜索
        form.on('submit(resets)', function (data) {
            $(".lay-header").find('select').val("");
            $(".lay-header").find('input').val("");
            var field = data.field;
            for (let key in field) {
                field[key] = ''
            }
            insTb.reload({where: field, page: {curr: 1}}, 'data');
        });
        // option渲染
        function loadSelectHtml(data, tips, htmltarget, type) {
            let html = ' <option value>' + tips + '</option>';
            if (!data || data == null) {
                return;
            }
            for (let i = 0; i < data.length; i++) {
                if (type === 0) {
                    html += `<option value='${data[i].id}'>${data[i].name}</option>`;
                } else if (type === 1) {
                    html += `<option value='${data[i].id}'>${data[i].corporateName}</option>`;
                }
            }

            $("form select[name='" + htmltarget + "']").html(html);
            form.render('select');
        }
    });
</script>